package com.pzsh.handler;


import com.pzsh.enums.CodeBaseEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

public class EnumJsonDeserializer extends JsonDeserializer<CodeBaseEnum> {
    @Override
    @SuppressWarnings("unchecked")
    public CodeBaseEnum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        JsonNode node = jp.getCodec().readTree(jp);
        String currentName = jp.currentName();
        Object currentValue = jp.getCurrentValue();
        @SuppressWarnings("rawtypes")
        Class findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        CodeBaseEnum valueOf = null;

        if (node.has("code")) {
            valueOf = (CodeBaseEnum) CodeBaseEnum.codeOf(findPropertyType, node.get("code").asInt());
        } else {
            valueOf = (CodeBaseEnum) CodeBaseEnum.codeOf(findPropertyType, node.textValue());
        }
        return valueOf;
    }
}
